package com.example.mcdonaldapplication.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.example.mcdonaldapplication.R
import com.example.mcdonaldapplication.databinding.ActivityOrderBinding
import com.example.mcdonaldapplication.fragment.*
import com.example.mcdonaldapplication.info.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.io.IOException
import kotlin.concurrent.thread

class OrderActivity : AppCompatActivity() {
    private lateinit var binding:ActivityOrderBinding
    private val goodsList = ArrayList<GoodsInfo>()
    private val serverIP = ServerIP.getIp()
    private val hamburgerList : ArrayList<GoodsInfo> = ArrayList()
    private val chickenList : ArrayList<GoodsInfo> = ArrayList()
    private val bucketList : ArrayList<GoodsInfo> = ArrayList()
    private val dessertList : ArrayList<GoodsInfo> = ArrayList()
    private val drinkList : ArrayList<GoodsInfo> = ArrayList()
    private lateinit var fragmentList:ArrayList<Fragment>
    private lateinit var viewPager2: ViewPager2 //binding在这里还没有绑定！！
    private var hamburgerFragment= HamburgerFragment()
    private var chickenFragment= ChickenFragment()
    private var dessertFragment= DessertFragment()
    private var drinkFragment= DrinkFragment()
    private var bucketFragment= BucketFragment()
    var totalprice = 0
    var totalnum = 0
    private var i = 0
    private val cartList = ArrayList<CartInfo>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityOrderBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()
        viewPager2=binding.rvGoods
        getCart()
        getAllGoods()
        initBanner()
        initClick()
        //点击选好了跳转到订单界面
        binding.tvAdd.setOnClickListener {
            if(totalprice == 0){
                Toast.makeText(this, "请先点餐噢O_o", Toast.LENGTH_SHORT).show()
            }else{
                val address = intent.getStringExtra("address")
                val intent = Intent(this,IndentActivity::class.java)
                intent.putExtra("price",totalprice)
                intent.putExtra("address", address)
                intent.putExtra("from", "order")
                finish()
                startActivity(intent)
            }
        }

        // 查看购物车
        binding.flCart.setOnClickListener {
            onResume()
            if(binding.llDialog.visibility == View.VISIBLE){
                binding.llDialog.visibility = View.GONE
            }else{
                binding.llDialog.visibility = View.VISIBLE
            }
        }
        // 取消购物车dialog
        binding.llDialog.setOnClickListener {
            binding.llDialog.visibility = View.GONE
        }
        // 清空所有商品
        binding.llClear.setOnClickListener {
            val editor = getSharedPreferences("cart", Context.MODE_PRIVATE).edit()
            editor.clear()
            editor.apply()
            onResume()
        }
    }

    private fun initBanner(){
        val banner: Banner<BannerImageBean, BannerImageAdapter<BannerImageBean>> = binding.banner as Banner<BannerImageBean, BannerImageAdapter<BannerImageBean>>
        banner.setAdapter(object: BannerImageAdapter<BannerImageBean>(BannerImageBean.testData3) {
            override fun onBindView(holder: BannerImageHolder, data: BannerImageBean, position: Int, size: Int) {
                //图片加载自己实现
                Glide.with(holder.itemView)
                    .load(data.imageRes)
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(30)))
                    .into(holder.imageView) }
        }).addBannerLifecycleObserver(this).indicator = CircleIndicator(this)
    }

    private fun getAllGoods(){
        thread {
            val formBody: FormBody = FormBody.Builder()
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIP}/goods/queryAll")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJSONWithGSON(responseData)
        }
    }

    private fun parseJSONWithGSON(jsonData: String) {
        val jsonObject = JSONObject(jsonData)
        val message = jsonObject.getString("message")
        val data = jsonObject.getString("data")
        if (message == "查询成功") {
            val gson = Gson()
            val typeOf = object : TypeToken<List<GoodsInfo>>() {}.type
            val goodsInfoList = gson.fromJson<List<GoodsInfo>>(data, typeOf)
            for (good in goodsInfoList) {
                when (good.goodType) {
                    0 -> hamburgerList.add(good)
                    1 -> chickenList.add(good)
                    2 -> bucketList.add(good)
                    3 -> dessertList.add(good)
                    4 -> drinkList.add(good)
                }
                goodsList.add(good)
            }
        }

        runOnUiThread{
            fragmentList=ArrayList()
            fragmentList.add(hamburgerFragment)
            fragmentList.add(chickenFragment)
            fragmentList.add(bucketFragment)
            fragmentList.add(dessertFragment)
            fragmentList.add(drinkFragment)
            viewPager2.offscreenPageLimit=fragmentList.size-1//防止item被重复加载
            val adapter= MyAdapter(this)
            //adapter.notifyDataSetChanged()
            viewPager2.adapter=adapter
            viewPager2.orientation= ViewPager2.ORIENTATION_VERTICAL
            viewPager2.currentItem=0
            //    }
            //
            //    private fun initRecycleView() {

            hamburgerFragment.prepare(LinearLayoutManager(this),GoodsAdapter(hamburgerList, "order", this))
            chickenFragment.prepare(LinearLayoutManager(this),GoodsAdapter(chickenList, "order", this))
            bucketFragment.prepare(LinearLayoutManager(this),GoodsAdapter(bucketList, "order", this))
            dessertFragment.prepare(LinearLayoutManager(this),GoodsAdapter(dessertList, "order", this))
            drinkFragment.prepare(LinearLayoutManager(this),GoodsAdapter(drinkList, "order", this))
        }
    }

    @SuppressLint("SetTextI18n")
    private fun getCart() {
        try {
            val prefs = getSharedPreferences("cart", Context.MODE_PRIVATE)
            i = 0
            for (goods in goodsList) {
                val num = prefs.getInt("${goods.name}num", 0)
                val price = prefs.getString("${goods.name}price", "0")!!
                val img = prefs.getString("${goods.name}img", "0")!!
                val gid = prefs.getString("${goods.name}gid", "0")!!
                if (num >= 1) {
                    cartList.add(i, CartInfo(gid, goods.name, num, price, img))
                    i++
                    totalnum += num
                    totalprice += num * price.toInt()
                }
            }
            //合计费用
            binding.tvTotalPrice.text = "合计:¥${totalprice}"
            //商品数量
            binding.tvTotalNum.text = "$totalnum"
            binding.rvChosenGoods.layoutManager = LinearLayoutManager(this)
            binding.rvChosenGoods.adapter = CartAdapter(cartList, this)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    private fun initClick(){
        binding.llHamburger.setBackgroundResource(R.drawable.bg_white_round_radius_10)
        binding.llHamburger.setOnClickListener{
            setColor()
            binding.llHamburger.setBackgroundResource(R.drawable.bg_white_round_radius_10)
            viewPager2.currentItem = 0
        }
        binding.llChicken.setOnClickListener{
            setColor()
            binding.llChicken.setBackgroundResource(R.drawable.bg_white_round_radius_10)
            viewPager2.currentItem = 1
        }
        binding.llBucket.setOnClickListener{
            setColor()
            binding.llBucket.setBackgroundResource(R.drawable.bg_white_round_radius_10)
            viewPager2.currentItem = 2
        }
        binding.llDessert.setOnClickListener{
            setColor()
            binding.llDessert.setBackgroundResource(R.drawable.bg_white_round_radius_10)
            viewPager2.currentItem = 3
        }
        binding.llDrink.setOnClickListener{
            setColor()
            binding.llDrink.setBackgroundResource(R.drawable.bg_white_round_radius_10)
            viewPager2.currentItem = 4
        }
    }

    private fun setColor(){
        binding.llHamburger.setBackgroundResource(R.color.mcd_grey)
        binding.llChicken.setBackgroundResource(R.color.mcd_grey)
        binding.llBucket.setBackgroundResource(R.color.mcd_grey)
        binding.llDessert.setBackgroundResource(R.color.mcd_grey)
        binding.llDrink.setBackgroundResource(R.color.mcd_grey)
    }

    private  inner class MyAdapter(fa: FragmentActivity): FragmentStateAdapter(fa) {
        override fun getItemCount(): Int {
            return fragmentList.size
        }

        override fun createFragment(position: Int): Fragment {
            return fragmentList[position]
        }
    }

    override fun onResume() {
        super.onResume()
        cartList.clear()
        totalprice = 0
        totalnum = 0
        getCart()
    }
}